package generates

import (
	"bytes"
	"encoding/base64"
	"strings"

	"github.com/devfeel/dotweb/framework/crypto"
	"strconv"
)

// NewAccessGenerate create to generate the access token instance
func NewAccessGenerate() *AccessGenerate {
	return &AccessGenerate{}
}

// AccessGenerate generate the access token
type AccessGenerate struct {
}

// Token based on the UUID generated token
func (ag *AccessGenerate) Token(data *GenerateBasic, isGenRefresh bool) (access, refresh string, err error) {
	buf := bytes.NewBufferString(data.ClientID)
	buf.WriteString(data.ClientSecret)
	buf.WriteString(strconv.FormatInt(data.CreateAt.UnixNano(), 10))

	access = base64.URLEncoding.EncodeToString([]byte(cryptos.GetMd5String(buf.String())))
	access = strings.ToUpper(strings.TrimRight(access, "="))
	if isGenRefresh {
		refresh = base64.URLEncoding.EncodeToString([]byte(cryptos.GetUUID()))
		refresh = strings.ToUpper(strings.TrimRight(refresh, "="))
	}

	return
}
